﻿using System;
using System.Web;
using ImageStoreNET.Developer;
using ImageStoreNET.Developer.Core;
using ImageStoreNET.Developer.Filters;
using System.Text;

namespace EPiServer.Municipality.Templates.Pages {
    public partial class Gallery : TemplatePage {
        /* *******************************************************************
         * Properties
         * *******************************************************************/
        #region protected int RootAlbumId
        /// <summary>
        /// Gets the RootAlbumId of the Gallery
        /// </summary>
        /// <value></value>
        protected int RootAlbumId
        {
            get
            {
                if (IsValue("AlbumRoot"))
                {
                    return (int)CurrentPage["AlbumRoot"];
                }
                return 0;
            }
        }
        #endregion
        #region protected int NrOfFiles
        /// <summary>
        /// Gets the NrOfFiles of the Gallery
        /// </summary>
        /// <value></value>
        protected int NrOfFiles
        {
            get
            {
                if (IsValue("NrOfFiles"))
                {
                    return (int)CurrentPage["NrOfFiles"];
                }
                return 12;
            }
        }
        #endregion
        /* *******************************************************************
         * Methods
         * *******************************************************************/
        #region override protected void OnInit(EventArgs e)
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        #endregion
        #region private void InitializeComponent()
        /// <summary>
        /// 
        /// </summary>
        private void InitializeComponent()
        {
            Load += Page_Load;
            AlbumControl.Filter += AlbumControl_Filter;
        }
        #endregion
        #region protected string GetAlbumCover(IVAlbumData album)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="album"></param>
        /// <returns></returns>
        protected string GetAlbumCover(IVAlbumData album) {
            var images = IVDataFactory.GetFiles(album.Id, false);
            if (images != null && images.Count > 0) {
                var image = images[0];
                var ub = new IVUrlBuilder { Id = image.Id, Width = 140, Height = 140, AspectRatio = 1 };
                return ub.ToString();
            }
            return null;
        }
        #endregion
        #region protected string GetPreviewUrl(IVFileData image)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        protected string GetPreviewUrl(IVFileData image)
        {
            var ub = new IVUrlBuilder { Id = image.Id, Width = 800, Height = 600 };
            return ub.ToString();
        }
        #endregion
        #region protected string GetDownloadLinkUrl(IVConversionFormat format)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        protected string GetDownloadLinkUrl(IVConversionFormat format)
        {
            var ub = IVUrlBuilder.ParseUrl(format.LinkURL);
            ub.Download = true;
            return ub.ToString();
        }
        #endregion
        #region protected IVCategoryCollection GetCategories()
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected IVCategoryCollection GetCategories() {
            IVCategoryCollection selectedCategories = new IVCategoryCollection();
            IVCategoryCollection allCategories = IVDataFactory.GetAllCategories();
            string[] selectedIds = null;
            if (!String.IsNullOrEmpty(Request.QueryString["cat"]))
            {
                selectedIds = Request.QueryString["cat"].Split(',');
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<ul>");
            foreach (IVCategory category in allCategories)
            {
                string selected = null;
                if (selectedIds != null)
                {
                    foreach (string id in selectedIds)
                    {
                        if (id == category.Id.ToString())
                        {
                            selected = " checked=\"checked\"";
                            selectedCategories.Add(category);
                        }
                    }
                }
                sb.Append("<li>");
                sb.Append("<input id=\"cat_" + category.Id + "\" name=\"cat_" + category.Id + "\" type=\"checkbox\" value=\"" + category.Id + "\"" + selected + " />");
                sb.Append("<label for=\"cat_" + category.Id + "\">" + category.Name + "</label>");
                sb.Append("</li>");
            }
            sb.Append("</ul>");
            CategoryControl.Text = sb.ToString();
            return selectedCategories;
        }
        #endregion
        #region protected string AddCategoriesQueryString(string url)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        protected string AddCategoriesQueryString(string url)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string key in Request.Form)
            {
                if (key.StartsWith("cat"))
                {
                    if (!String.IsNullOrEmpty(Request.Form[key]))
                    {
                        sb.Append(Request.Form[key]);
                        sb.Append(",");
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
                return UriSupport.AddQueryString(url, "cat", sb.ToString());
            }
            return url;
        }
        #endregion
        #region protected string GetMetaData(IVFileData fileData, string name)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetMetaData(IVFileData fileData, string name)
        {
            return fileData.MetaData[name] != null ? fileData.MetaData[name].Value : string.Empty;
        }
        #endregion
        /* *******************************************************************
         *  Event methods 
         * *******************************************************************/
        #region protected void Page_Load(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the Page's Load event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        protected void Page_Load(object sender, EventArgs e) {

            ((MasterPages.Default)Master).CssClass = "gallery";

            if(HttpContext.Current.User.Identity.IsAuthenticated) {
                UploadAction.Visible = true;
            }

            if (Request.Form["query"] != null)
            {
                var query = Request.Form["query"];
                if (query.Equals(Translate("/municipality/templates/gallery/searchlabel")))
                {
                    query = "";
                }
                string url = UriSupport.AddQueryString(Request.Url.PathAndQuery, "q", query);
                url = AddCategoriesQueryString(url);
                Response.Redirect(url);
            }

            IVCategoryCollection categories = GetCategories();

            if (!String.IsNullOrEmpty(Request.QueryString["q"]) || !string.IsNullOrEmpty(Request.QueryString["cat"]))
            {
                IVFileDataCollection files = IVDataFactory.FindFilesWithCriteria(RootAlbumId, Request.QueryString["q"], categories, IVSearchConditions.Or, null, true);

                GalleryControl.DataSource = files;
                GalleryControl.DataBind();
                GalleryControl.Visible = true;
                return;
            }

            if (string.IsNullOrEmpty(Request["album"])) {
                AlbumControl.Visible = true;
                AlbumControl.DataBind();
            }
            else
            {
                GalleryControl.AlbumId = int.Parse(Request["album"]);
                GalleryControl.ResultType = (string)CurrentPage["ResultType"] ?? Translate("/municipality/templates/gallery/resulttype");
                GalleryControl.Visible = true;
                GalleryControl.DataBind();
            }
        }
        #endregion
        #region void AlbumControl_Filter(object sender, IVAlbumFilterEventArgs e)
        /// <summary>
        /// This method is called when the AlbumControl's Filter event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="IVAlbumFilterEventArgs"/> of the event.</param>
        void AlbumControl_Filter(object sender, IVAlbumFilterEventArgs e)
        {
            for (int i = 0; i < e.Albums.Count; i++)
            {
                if (e.Albums[i].NrOfFiles < 1)
                {
                    e.Albums.RemoveAt(i);
                    i--;
                }
            }
        }
        #endregion
    }
}